<?php

namespace addons\qingdongams\controller;

use addons\qingdongams\model\Email as EmailModel;
use addons\qingdongams\model\StaffSignIn;
use addons\qingdongams\model\Contacts;
use addons\qingdongams\model\File;
use PHPMailer\PHPMailer\PHPMailer;
use think\Db;
use think\Log;


/**
 * 发送邮件
 */
class Sendemail extends StaffApi {
	protected $noNeedLogin = [];
	protected $noNeedRight = [];
    protected $formater = ['gif','jpeg','png','jpg','bmp'];


    // 草稿箱
    public function draftsEmail(){
        $ids = input('ids');
        $content = input('content','');// 内容
        $theme = input('theme','');// 主题
        $receiver = input('receiver','');// 收件人 ,隔开
        $copyor = input('copyor','');// 收件人 ,隔开
        $receiveIds = [];
        $model = new EmailModel();
        if($receiver){
            $receiveIds = Contacts::where('email','in',explode(',',$receiver))->column('id');
        }
        $save = [
            'send_id'=>$this->auth->id,
            'send_name'=>$this->auth->name,
            'receiver'=>$receiver,
            'receive_id'=>implode(',',$receiveIds),
            'copyor'=>$copyor,
            'theme'=>$theme,
            'content'=>$content,
            'is_send'=>0,
            'file_ids'=>$ids,
        ];
        if($model->save($save) === false){
            Log::write('存库失败数据：'.$model->getLastSql());
        }
        $this->success('存库成功');

    }

    // 草稿箱列表
    public function draftsEmails(){
        $limit = input("limit/d", 10);
        $where['send_id'] = $this->auth->id;
        $where['is_send'] = 0;
        $email = new EmailModel();
        $list = $email->where($where)->field('createtime,updatetime,imgs,attach',true)->paginate($limit);
        $this->success('',$list);
    }
    // 发送邮箱
    public function sendEmail(){
        $emailId = input('id/d',0); // 邮件id
        $fileIds = input('ids');// 附件id
        $content = input('content','');// 内容
        $theme = input('theme','');// 主题
        $receiver = input('receiver');// 收件人 ,隔开
        $copyor = input('copyor','');// 收件人 ,隔开
        $params =  $this->request->post();
        Log::write('发送参数'.json_encode($params));
        if(!isset($theme) || !$theme){
            $this->error('请输入邮箱发送主题');
        }
        if(!isset($content) || !$content){
            $content = $theme;
        }
        if(!isset($receiver) || !$receiver){
            $this->error('请输入接收人');
        }
        $imgs = $fujian = [];
        if($fileIds){
            $ids = explode(',',$fileIds);
            $filemodel = new File();
            $list       = $filemodel->where('id','in',$ids)->column('file_path');
            foreach ($list as $k=>$v){
                $geshi = substr(strrchr($v, '.'), 1);
                $file = ROOT_PATH.'public'.$v;
                if(in_array($geshi,$this->formater)){
                    $imgs[] = $file;
                }else{
                    $fujian[] = $file;
                }
            }
        }
        Log::write('开始发送准备参数==='.$receiver.'---'.$theme.'===='.$content.'----'.$copyor);
        $res = $this->send_email(explode(',',$receiver),$theme,$content,$imgs,$fujian,explode(',',$copyor));
        Log::write('发送完毕结果==='.json_encode($res));
        if($res['error'] == 0){
            $receiveIds = $customerIds ='';
            $linkList = Contacts::where('email','in',explode(',',$receiver))->field('id,customer_id')->select();
            if(count($linkList)>0){
                $receiveIds = implode(',',array_column($linkList,'id'));
                $customerIds = implode(',',array_column($linkList,'customer_id'));
            }
            $model = new EmailModel();
            $save = [
                'send_id'=>$this->auth->id,
                'send_name'=>$this->auth->name,
                'receiver'=>$receiver,
                'receive_id'=>$receiveIds,
                'copyor'=>$copyor,
                'theme'=>$theme,
                'content'=>$content,
                'is_send'=>1,
                'imgs'=>implode(',',$imgs),
                'attach'=>implode(',',$fujian),
                'file_ids'=>$fileIds,
                'sendtime'=>date("Y-m-d H:i:s"),
            ];
            $data = [
                'staff_id' => $this->auth->id,
                'location' => '',
                'lng' => '',
                'lat' => '',
                'files' => $fileIds,
                'customer_id' => $customerIds,//客户id
                'relation_type' => StaffSignIn::CUSTOMER_TYPE,//日程类型 客户
                'relation_id' => $customerIds,//签到关联发送邮件id
                'relation_process' => '邮箱',//进度
                'content' => $theme,
                'distance' => '',
            ];
            $res = $result = true;
            Db::startTrans();
                if($emailId){
                    if(!$res = $model->isUpdate(true)->save($save,['id'=>$emailId])){
                        Log::write('发送成功，存库失败数据：'.json_encode($save).'---sql语句：'.$model->getLastSql());
                    }
                }else{
                    if(!$res = $model->save($save)){
                        Log::write('发送成功，存库失败数据：'.json_encode($save).'---sql语句：'.$model->getLastSql());
                    }
                }
                if(!$result = StaffSignIn::createSignIn($data)){
                    Log::write('发送成功，跟进记录失败数据：'.json_encode($save).'---sql语句：'.StaffSignIn::getLastSql());
                }
                if($res === false || $result === false){
                    Db::rollback();
                    $this->error('邮件发送成功,本地记录失败！');
                }else{
                    Db::commit();
                    $this->success('发送成功');
                }
        }else{
            $this->error('企业邮箱配置不正确');
        }
    }

    // 已发送列表
    public function getSendEmails()
    {
        $limit = input("limit/d", 10);
        $where['send_id'] = $this->auth->id;
        $where['is_send'] = 1;
        $email = new EmailModel();
        $list = $email->where($where)->field('createtime,updatetime,imgs,attach',true)->paginate($limit);
        $this->success('',$list);
    }









    /**
     * 发送邮件
     * @param  string $address 需要发送的邮箱地址 发送给多个地址需要写成数组形式
     * @param  string $subject 标题
     * @param  string $content 内容
     * @param  string $imgs 图片  发送给多个地址需要写成数组形式
     * @param  string $attach 附件  发送给多个地址需要写成数组形式
     * @return boolean       是否成功
     */
    function send_email($address,$subject,$content,$imgs='',$attach='',$copyor = []){
        $email_from_name = $this->auth->name;// 发件人
//        $email_smtp='smtp.163.com';// smtp 网易一般邮箱服务器地址
        $email_smtp='smtphz.qiye.163.com';// smtp 网易企业邮箱服务器地址
        $email_username=$this->auth->email;// 账号
        $email_password=$this->auth->email_code; // 密码  注意: 163和QQ邮箱是授权码；不是登录的密码

        $email_smtp_secure='ssl';// 链接方式 如果使用QQ邮箱；需要把此项改为  ssl
        $email_port= 465;// 端口 王一邮箱：25； 如果使用QQ邮箱；需要把此项改为  465
        if(empty($email_smtp) || empty($email_username) || empty($email_password) || empty($email_from_name)){
            return array("error"=>1,"message"=>'邮箱配置不完整');
        }

        $phpmailer=new PHPMailer();
        // 设置PHPMailer使用SMTP服务器发送Email
        $phpmailer->IsSMTP();
        // 设置设置smtp_secure
        $phpmailer->SMTPSecure=$email_smtp_secure;
        // 设置port
        $phpmailer->Port=$email_port;
        // 设置为html格式
        $phpmailer->IsHTML(true);
        // 设置邮件的字符编码'
        $phpmailer->CharSet='UTF-8';
        // 设置SMTP服务器。
        $phpmailer->Host=$email_smtp;
        // 设置为"需要验证"
        $phpmailer->SMTPAuth=true;
        // 设置用户名
        $phpmailer->Username=$email_username;
        // 设置密码
        $phpmailer->Password=$email_password;
        // 设置邮件头的From字段。
        $phpmailer->From=$email_username;
        // 设置发件人名字
        $phpmailer->FromName=$email_from_name;
        // 添加收件人地址，可以多次使用来添加多个收件人
        foreach($address as $add){
            $phpmailer->AddAddress(htmlspecialchars($add));
        }
        // 抄送人
        foreach($copyor as $copy){
            $phpmailer->addCC(htmlspecialchars($copy));
        }
        // 发送图片
        if(is_array($imgs)){
            foreach($imgs as $k=>$img){
                $phpmailer->addEmbeddedImage($img,'img_'.$k);
            }
        }else{
            $phpmailer->addEmbeddedImage($imgs,'img');
        }
        // 发送附件
        if(is_array($attach)){
            foreach($attach as $att){
                $phpmailer->addAttachment($att);
            }
        }else{
            $phpmailer->addAttachment($attach);
        }
        // 设置邮件标题
        $phpmailer->Subject=$subject;
        // 设置邮件正文
        $phpmailer->Body=$content;
        // 发送邮件。
        if(!$phpmailer->Send()) {
            $phpmailererror=$phpmailer->ErrorInfo;
            return array("error"=>1,"message"=>$phpmailererror);
        }else{
            return array("error"=>0);
        }
    }



}
